package com.baijia.authentication.principal;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.springframework.util.Assert;
/**
 * @title SimplePrincipal
 * @desc 初始化后，额外信息属性不可变， 这种信息，一般为配死的
 * @author caoliang
 * @date 2015年12月5日
 * @version 1.0
 */
public class SimplePrincipal implements Principal {

    private static final Map<String, Object> EMPTY_MAP = Collections
        .unmodifiableMap(new HashMap<String, Object>());

    private static final long serialVersionUID = -5265620187476296219L;

    private final String id;

    private Map<String, Object> attributes;

    public SimplePrincipal(final String id) {
        this(id, null);
    }

    public SimplePrincipal(final String id, final Map<String, Object> attributes) {
        Assert.notNull(id, "id cannot be null");
        this.id = id;

        this.attributes = attributes == null || attributes.isEmpty()
            ? EMPTY_MAP : Collections.unmodifiableMap(attributes);
    }

    /**
     * Returns an immutable map.
     */
    @Override
    public Map<String, Object> getAttributes() {
        return this.attributes;
    }

    @Override
    public String toString() {
        return "SimplePrincipal [id=" + id + ", attributes=" + attributes + "]";
    }

    @Override
    public int hashCode() {
        return super.hashCode() ^ this.id.hashCode();
    }

    @Override
    public final String getId() {
        return this.id;
    }

    @Override
    public boolean equals(final Object o) {
        if (o == null || !this.getClass().equals(o.getClass())) {
            return false;
        }

        final SimplePrincipal p = (SimplePrincipal) o;

        return this.id.equals(p.getId());
    }
}
